package com.eat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eat.constant.MessageConstant;
import com.eat.dto.UserLoginDTO;
import com.eat.entity.Employee;
import com.eat.entity.User;
import com.eat.exception.LoginFailedException;
import com.eat.mapper.UserMapper;
import com.eat.properties.WeChatProperties;
import com.eat.service.UserService;
import com.eat.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImp implements UserService {

    private static String WX_LOGIN = "";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

//        String openid = getOpenid(userLoginDTO);
        String openid =null;
        if (openid ==null){

            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);

        }

        User user=userMapper.getByOpenId(openid);

        if (user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }


        return user;
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String,String> hashMap = new HashMap<>();
        hashMap.put("appid",weChatProperties.getAppid());
        hashMap.put("secret",weChatProperties.getSecret());
        hashMap.put("js_code", userLoginDTO.getCode());
        hashMap.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, hashMap);

        JSONObject jsonObject=new JSONObject();
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
